package controller.log;

import controller.common.BaseController;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import response.CommonResult;
import util.DateUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 功能:
 * 作者: 洪世成
 * 日期: 2017/9/9
 * 版权所有: admin
 */
@Controller
@RequestMapping("log/log4jLog")
public class Log4jLogController extends BaseController {



    @RequiresPermissions("log:log4jLog:default")
    @RequestMapping("index")
    public String index() {
        return "log/log4jLog/index";
    }

    String basePath = "D:\\shzj_hong\\woking\\lib_source_jdk_tomacte_maven_addOther\\apache-tomcat-8.5.6\\logs";


    @RequiresPermissions("log:log4jLog:default")
    @ResponseBody
    @RequestMapping("select")
    public List select(

    ) throws Exception {
        JSONArray jsonArray = new JSONArray();
        File file = new File(basePath);
        if (file.isDirectory()) {
            String[] files = file.list();
            Arrays.sort(files);
            JSONObject jsonObject = new JSONObject();
            for (int i = 0; i < files.length; i++) {
                jsonObject.put("name", files[i]);
                jsonArray.add(jsonObject);
            }
//            for(int i=files.length-1;i>=0;i--){
//                jsonObject.put("name",files[i]);
//                jsonArray.add(jsonObject);
//            }

            return jsonArray;
        } else {
            return null;
        }
    }

    @RequiresPermissions("log:log4jLog:default")
    @ResponseBody
    @RequestMapping("deleteMonthAgo")
    public CommonResult deleteMonthAgo() throws Exception {
        CommonResult commonResult = new CommonResult();
        String[] fileNames = new File(basePath).list();
        String newTime = DateUtil.date2String(DateUtil.moveDate(new Date(), -30), DateUtil.DATE_PATTEN);
        for (String fileName : fileNames) {
            int beginIndex = fileName.indexOf(".log_") + 5;
            int endIndex = fileName.lastIndexOf(".log");
            if (beginIndex > 4) {
                String createTime = fileName.substring(beginIndex, endIndex);
                if (newTime.compareTo(createTime) > 0) {
                    File file = new File(basePath + File.separator + fileName);
                    System.out.println(fileName);
                    if (file.isFile()) {
                        boolean result = file.delete();
                    }
                }
            }
        }
        return commonResult.setSuccess();
    }

    @RequiresPermissions("log:log4jLog:default")
    @ResponseBody
    @RequestMapping("delete")
    public CommonResult delete(String fileName) throws Exception {
        CommonResult commonResult = new CommonResult();
        File file = new File(basePath + File.separator + fileName);
        if (file.exists() && !file.isDirectory()) {
            commonResult.setStatus(file.delete() ? 1 : 0);
        } else {
            commonResult.addMessage("文件不存在");
            commonResult.setError();
        }
        return commonResult;
    }

    @RequiresPermissions("log:log4jLog:default")
    @RequestMapping("editDlg")
    public String editDlg(String fileName, Map map) throws Exception {
        File file = new File(basePath + File.separator + fileName);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }

        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

        String lineString;
        StringBuffer buffer = new StringBuffer();
        while ((lineString = bufferedReader.readLine()) != null) {
            buffer.append(lineString);
            buffer.append("\r\n");
        }
        if (buffer.length() > 1024 * 1024) {
            map.put("html", "文件内容过大，请下载后查看！！");
        } else {
            map.put("html", buffer.toString());
        }
        return "log/log4jLog/editDlg";
    }


    @RequiresPermissions("log:log4jLog:default")
    @RequestMapping("downLoad")
    public void downLoad(String fileName, HttpServletResponse response) throws Exception {
        File file = new File(basePath + File.separator + fileName);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }
        InputStream inputStream = new FileInputStream(file);

        response.reset();

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        OutputStream outputStream = response.getOutputStream();

        byte[] bytes = new byte[1042];
        int total;
        while ((total = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, total);
        }
        inputStream.close();
        outputStream.close();


    }


}
